﻿/****************
* Authored by Zhuo "Wizcas" Chen
* 2018 © Wubi.fun all rights reserved
*****************/

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using Wubi.Utils;

public class ResManager : MonoBehaviour
{
    static ResManager _instance;
    public static ResManager instance { get { return _instance ?? (_instance = FindObjectOfType<ResManager>()); } }

    [SerializeField] Res[] resStorage;
    public System.Action<IEnumerable<Res>> onStorageUpdated;

    private void Awake()
    {
        resStorage = Database.instance.resList;
    }

    public Res Get(string id)
    {
        return resStorage.FirstOrDefault(r => r.id == id);
    }

    public int IndexOf(string id)
    {
        int index = 0;
        foreach (var res in resStorage)
        {
            if (res.id == id) return index;
            index++;
        }
        return -1;
    }

    public void Clear()
    {
        resStorage.Foreach((res, i) => resStorage[i].amount = 0);
        if (onStorageUpdated != null) onStorageUpdated(resStorage);
    }

    public void Set(string id, int amount)
    {
        var i = IndexOf(id);
        if (i >= 0) resStorage[i].amount = amount;
        if (onStorageUpdated != null) onStorageUpdated(resStorage);
    }

    public void Add(string id, int amount)
    {
        var i = IndexOf(id);
        if (i >= 0) resStorage[i].amount += amount;
        if (onStorageUpdated != null) onStorageUpdated(resStorage);
    }

    public bool IsEnough(IEnumerable<Res> requirements)
    {
        foreach(var req in requirements)
        {
            var i = IndexOf(req.id);
            var abs = Mathf.Abs(req.amount);
            if (i >= 0 && resStorage[i].amount < abs) return false;
        }
        return true;
    }

    public int CalculateScore()
    {
        int score = 0;
        foreach(var res in resStorage)
        {
            if (!res.isValid) continue;
            score += res.score * res.amount;
        }
        return score;
    }
}